package com.aerospace.rpc5;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;

/**
 * @Author: Aerospace
 * @Date: 2021/5/12 22:58
 * @Description: Dream begins
 */
public class Stub {
    public static Object getSub(Class c){
        InvocationHandler handler = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Socket socket = new Socket("127.0.0.1",8099);
                ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());

                //添加了服务类型的传输
                oos.writeUTF(c.getName());//服务类型
                oos.writeUTF(method.getName());
                oos.writeObject(method.getParameterTypes());
                oos.writeObject(args);
                oos.flush();

                //接收服务端返回的结果，object读入
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                Object obj = ois.readObject();
                return obj; //改为返回通用对象
            }
        };
        Object o = Proxy.newProxyInstance(c.getClassLoader(),new Class[]{c},handler);
        System.out.println(o.getClass().getName());
        System.out.println(o.getClass().getInterfaces());
        return o;
    }
}
